package com.android.myfilm.share;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class ShareOnFacebook extends Activity {
	
	private static final String APP_ID = "263257430426866";
	private static final String[] PERMISSIONS = { "offline_access", "publish_stream", "user_photos", "publish_checkins",
    "photo_upload" };

	private static final String TOKEN = "access_token";
    private static final String EXPIRES = "expires_in";
    private static final String KEY = "facebook-credentials";
    
    private static final String CAPTION = "MyFilm";
    private static final String DESCRIPTION = "I'm watching ";
    
    private Facebook facebook;
	private Activity activity;
	
	public ShareOnFacebook(Activity activity) {
		if (activity != null) {
			this.activity = activity;
		}
	}
	
	private boolean saveCredentials(Facebook facebook) {
		Editor editor = this.activity.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
    	editor.putString(TOKEN, facebook.getAccessToken());
		editor.putLong(EXPIRES, facebook.getAccessExpires());
    	return editor.commit();
	}

	private boolean restoreCredentials(Facebook facebook) {
    	SharedPreferences sharedPreferences = this.activity.getSharedPreferences(KEY, Context.MODE_PRIVATE);
    	facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
    	facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
    	return facebook.isSessionValid();
	}
	
	public void doNotShare(){
		finish();
	}
	
	public void share(Bundle params){
		facebook = new Facebook(APP_ID);
		restoreCredentials(facebook);
		
		if (! facebook.isSessionValid()) {
			loginAndPostToWall(params);
		}
		else {
//			postToWall(messageToPost);
			postCustomMessage(params);
			
		}
	}

	private void loginAndPostToWall(Bundle params){
		 facebook.authorize(this.activity, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener(params));
	}
	
	@Deprecated
	private void postToWall(String message){
		Bundle parameters = new Bundle();
		parameters.putString("message", message);
		parameters.putString("description", "topic share");

		try {
			facebook.request("me");
			String response = facebook.request("me/feed", parameters, "POST");
			
//			facebook.dialog(MyFilmActivity.this, "feed", parameters, new PostMessageDialogListener());
			
			String accessToken = facebook.getAccessToken();
			
			System.out.println(accessToken);
			
			Log.d("Tests", "got response: " + response);
			
			if (response == null || response.equals("") || response.equals("false")) {
				showToast("Blank response.");
			}
			else {
				showToast("Message posted to your facebook wall!");
			}
			finish();
		} catch (Exception e) {
			showToast("Failed to post to wall!");
			e.printStackTrace();
			finish();
		}
	}
	
	private void postCustomMessage(Bundle params) {
		Bundle _params = new Bundle();
		_params.putString("caption", params.getString("title"));
        _params.putString("description", DESCRIPTION + params.getString("title"));
        _params.putString("picture", params.getString("poster"));
		
		facebook.dialog(this.activity, "feed", _params, new DialogListener() {
			
			@Override
			public void onFacebookError(FacebookError e) {
				showToast("ERROR " + e.getMessage());
			}
			
			@Override
			public void onError(DialogError e) {
				showToast("ERROR " + e.getMessage());
			}
			
			@Override
			public void onComplete(Bundle values) {
				showToast("Complete");
			}
			
			@Override
			public void onCancel() {
			}
		});
	}

	class LoginDialogListener implements DialogListener {
		private Bundle params;
		
		public LoginDialogListener(Bundle params) {
			this.params = params;
		}
	    public void onComplete(Bundle values) {
	    	saveCredentials(facebook);
//			postToWall(messageToPost);
	    	postCustomMessage(this.params);
	    }
	    
	    public void onFacebookError(FacebookError error) {
	    	showToast("Authentication with Facebook failed!");
	        finish();
	    }
	    
	    public void onError(DialogError error) {
	    	showToast("Authentication with Facebook failed!");
	        finish();
	    }
	    
	    public void onCancel() {
	    	showToast("Authentication with Facebook cancelled!");
	        finish();
	    }
	}
	
	class PostMessageDialogListener implements DialogListener {
	    public void onComplete(Bundle values) {
	    	showToast("Message posted on facebook... hopefully.");
		}
	    
	    public void onFacebookError(FacebookError error) {
	    	showToast("Authentication with Facebook failed!");
	        finish();
	    }
	    
	    public void onError(DialogError error) {
	    	showToast("Authentication with Facebook failed!");
	        finish();
	    }
	    
	    public void onCancel() {
	    	showToast("Authentication with Facebook cancelled!");
	        finish();
	    }
	}

	private void showToast(String message){
		Toast.makeText(this.activity.getApplicationContext(), message, Toast.LENGTH_LONG).show();
	}

}
